//
//  FriendDidSyncEventProcessor.swift
//  app_rn_frontend
//
//  Created by 鱼涛 on 2017/12/13.
//  Copyright © 2017年 Facebook. All rights reserved.
//

import Foundation
import WCDBSwift

class ContactListDidSyncEventProcessor: EventProcessorProtocol {
    static let instance = ContactListDidSyncEventProcessor()

    private init() {
    }

    private let service = ContactService()

    private let queue = DispatchQueue(label: "com.tst.db",qos:.background)

    func process(params: Dictionary<String, Any>?) throws {
        do {
            guard AppStatusManager.instance.userLoginStatus.0 && AppStatusManager.instance.userLoginStatus.1 != nil && AppStatusManager.instance.userLoginStatus.1 != 0 else {
                throw ProcessError.LoginStatusError
            }

            guard let pathForUserDB = AppStatusManager.instance.urlForUserDB?.path else {
                throw ProcessError.InvalidParamError
            }

            guard let friends = params?["friends"] as? [Dictionary<String, Any>] else {
                throw ProcessError.InvalidParamError
            }

            let df = DateFormatter()
            df.dateFormat = "yyyy-MM-dd HH:mm:ss"
            let nowString = "\(df.string(from: Date()))"

            let db = Database(at: pathForUserDB)
            try db.run(transaction: { [unowned self]_ in
                try ContactDao.updateAllFriendDeleted()
                for friend in friends {
                    let userId = friend["userId"] as! Int
                    let name = friend["name"] as! String
                    let remarkName = friend["name"] as? String ?? nil
//                    let avatar = friend["avatar"] as? String ?? ""
                    if let friendInDb:Contact = try ContactDao.getContact(userId){
                        friendInDb.remarkName = remarkName
//                        friendInDb.avatar = avatar
                        friendInDb.friend = true
                        friendInDb.canAddGroup = true
                        friendInDb.deleted = 0
                        try ContactDao.saveOrUpdate(contact: friendInDb, updateFields: [Contact.CodingKeys.deleted,Contact.CodingKeys.friend,Contact.CodingKeys.canAddGroup,Contact.CodingKeys.avatar,Contact.CodingKeys.name,Contact.CodingKeys.remarkName])
                    }else {
                        let friendToSave = Contact.addNewFriend(userId: userId, name: name,remarkName: name)
                        try db.insert(friendToSave, intoTable: Contact.table)
                    }
                    self.service.syncUserInfo(userId,queue:queue)
                }
            })
        } catch {
            throw error
        }
    }
}
